package com.hais1992.oneday.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import android.os.AsyncTask;

import com.hais1992.oneday.common.Config;

/**
 * 网络异步     POST、GET 访问请求
 * @author Hello_海生
 * @date 2014年5月20日
 */
public class GetHttpData {

	/**
	 * 请求数据
	 * @param url		//请求的URL地址
	 * @param method	//请求的方法， POST、GET
	 * @param map		//数据
	 * @param netCallback	//回调函数
	 */
	public GetHttpData(final String url,final String method,final Map<String, String> map,final GetCallback getCallback){
		//异步加载
		new AsyncTask<Void, Void, String>(){
			@Override
			protected String doInBackground(Void... params) {
				StringBuffer paramsStr = new StringBuffer();
				//把 参数 组合成 get 字符串 如  id=2&name=hais&password=123
				for (Object o : map.keySet()) {
					   paramsStr.append(o).append("=").append(map.get(o)).append("&");
				}
				try {
					URLConnection uc = null;
					
					if("POST".equals(method)){
						uc= new URL(url).openConnection();	//打开URL链接
						uc.setDoOutput(true);
						BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(uc.getOutputStream(), Config.CHARSET));	
						bw.write(paramsStr.toString());
						bw.flush();
					}else if("GET".equals(method)){
						uc = new URL(url+"?"+paramsStr.toString()).openConnection();
					}
					System.out.println("post:"+uc.toString());
					//获取请求结果
					BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream(),Config.CHARSET));
					String line= null;
					StringBuffer result = new StringBuffer();
					while ((line=br.readLine())!=null) {
						result.append(line);
					}
					return result.toString();	//返回请求结果
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				return null;
			}
			
			@Override
			protected void onPostExecute(String result) {
				if(result!=null){	//请求成功
					if(getCallback!=null){
						getCallback.onSuccess(result);
					}
				}
				super.onPostExecute(result);
			}
			
		}.execute();

	}
	
	//请求成功 回掉
	public static interface GetCallback{
		void onSuccess(String result);
	}
	
}
